import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Popconfirm, message, Modal, Dropdown, Tree } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MoreOutlined, AppstoreOutlined } from '@ant-design/icons';
import { getCategoryList, deleteCategory, updateCategoryStatus } from '@/services/courseManagementApi';
import CategoryForm from './components/CategoryForm';

const CategoryList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [categoryFormVisible, setCategoryFormVisible] = useState(false);
  const [currentCategory, setCurrentCategory] = useState<COURSE.CategoryModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');
  const [treeViewVisible, setTreeViewVisible] = useState(false);
  const [categoryTree, setCategoryTree] = useState<any[]>([]);

  // 状态标签颜色映射
  const statusColorMap = {
    active: 'green',
    inactive: 'orange',
  };

  // 表格列定义
  const columns: ProColumns<COURSE.CategoryModel>[] = [
    {
      title: '分类ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      width: 200,
      copyable: true,
    },
    {
      title: '分类描述',
      dataIndex: 'description',
      width: 300,
      search: false,
      ellipsis: true,
    },
    {
      title: '父分类',
      dataIndex: 'parent_name',
      width: 150,
      search: false,
      render: (text) => text || '顶级分类',
    },
    {
      title: '排序',
      dataIndex: 'sort_order',
      width: 80,
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      valueType: 'select',
      valueEnum: {
        active: { text: '启用', status: 'Success' },
        inactive: { text: '禁用', status: 'Warning' },
      },
      render: (_, record) => (
        <Tag color={statusColorMap[record.status]}>
          {record.status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '课程数量',
      dataIndex: 'course_count',
      width: 100,
      search: false,
      render: (count) => count?.toLocaleString() || 0,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          size="small"
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'status',
                label: record.status === 'active' ? '禁用' : '启用',
                onClick: () => handleStatusChange(record),
              },
              {
                key: 'addChild',
                label: '添加子分类',
                onClick: () => handleAddChild(record),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 处理编辑
  const handleEdit = (record: COURSE.CategoryModel) => {
    setCurrentCategory(record);
    setEditMode('edit');
    setCategoryFormVisible(true);
  };

  // 处理添加子分类
  const handleAddChild = (record: COURSE.CategoryModel) => {
    setCurrentCategory({ parent_id: record.id } as COURSE.CategoryModel);
    setEditMode('create');
    setCategoryFormVisible(true);
  };

  // 处理状态变更
  const handleStatusChange = (record: COURSE.CategoryModel) => {
    const newStatus = record.status === 'active' ? 'inactive' : 'active';
    const actionText = newStatus === 'active' ? '启用' : '禁用';
    
    Modal.confirm({
      title: `确认${actionText}`,
      content: `确定要${actionText}分类 "${record.name}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await updateCategoryStatus(record.id, newStatus);
          message.success(`分类${actionText}成功`);
          actionRef.current?.reload();
        } catch (error) {
          message.error(`分类${actionText}失败`);
        }
      },
    });
  };

  // 处理删除
  const handleDelete = (record: COURSE.CategoryModel) => {
    if (record.course_count && record.course_count > 0) {
      message.warning('该分类下还有课程，无法删除');
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除分类 "${record.name}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteCategory(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentCategory(undefined);
    setEditMode('create');
    setCategoryFormVisible(true);
  };

  // 显示树形结构
  const handleShowTree = async () => {
    try {
      const response = await getCategoryList({ page: 1, limit: 1000 });
      const categories = response.data.list;
      
      // 构建树形结构
      const buildTree = (parentId: number | null = null): any[] => {
        return categories
          .filter(cat => cat.parent_id === parentId)
          .map(cat => ({
            title: (
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span>{cat.name}</span>
                <Space>
                  <Tag color={statusColorMap[cat.status]} size="small">
                    {cat.status === 'active' ? '启用' : '禁用'}
                  </Tag>
                  <span style={{ fontSize: '12px', color: '#666' }}>
                    {cat.course_count || 0}门课程
                  </span>
                </Space>
              </div>
            ),
            key: cat.id,
            children: buildTree(cat.id),
          }));
      };

      setCategoryTree(buildTree());
      setTreeViewVisible(true);
    } catch (error) {
      message.error('加载分类树失败');
    }
  };

  return (
    <PageContainer>
      <ProTable<COURSE.CategoryModel>
        headerTitle="分类列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建分类
          </Button>,
          <Button
            key="tree"
            icon={<AppstoreOutlined />}
            onClick={handleShowTree}
          >
            树形结构
          </Button>,
        ]}
        request={async (params, sort) => {
          const response = await getCategoryList({
            page: params.current,
            limit: params.pageSize,
            name: params.name,
            status: params.status,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 分类表单弹窗 */}
      <CategoryForm
        visible={categoryFormVisible}
        mode={editMode}
        initialValues={currentCategory}
        onCancel={() => setCategoryFormVisible(false)}
        onSuccess={() => {
          setCategoryFormVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 树形结构弹窗 */}
      <Modal
        title="分类树形结构"
        open={treeViewVisible}
        onCancel={() => setTreeViewVisible(false)}
        footer={[
          <Button key="close" onClick={() => setTreeViewVisible(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        <Tree
          treeData={categoryTree}
          defaultExpandAll
          showLine
        />
      </Modal>
    </PageContainer>
  );
};

export default CategoryList;
